package com.py.credit.controller;

import com.alibaba.fastjson.JSONArray;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.constant.ResourcePath;
import com.py.credit.entity.DictDetailEntity;
import com.py.credit.entity.ReportCustom;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.RepQTGetEnum;
import com.py.credit.entity.enums.RepQTGetHistory;
import com.py.credit.entity.enums.ReportEnum;
import com.py.credit.service.*;
import com.py.credit.utils.*;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

@RestController
@RequestMapping(value = "/reportGet")
public class ReportGetController {
    // 报告类型常量
    private static final String BGLX = "BGLX";
    // 报告
    private static final String REPORT_COUNT_ID = "report_count";
    // 前台报告
    private static final String REPORT_HISTORY_COUNT_ID = "report_hsitpry_count";
    // 前台报告历史
    private static final String QT_REPORT_HISTORY_COUNT = "qt_report_hsitpry_count";
    @Value("${absolutepath}")
    private String absolutepath;

    @Value("${pdfJsPath}")
    private String pdfJsPath;

    @Value("${googlePath}")
    private String googlePath;

    @Value("${pdfPagePath}")
    private String pdfPagePath;

    @Value("${pdfForXypjPagePath}")
    private String pdfForXypjPagePath;

    @Value("${pdfForXypjPagePathYz}")
    private String pdfForXypjPagePathYz;

    @Autowired
    private XypjRemoteBaseService xypjRemoteBaseService;
    @Autowired
    private GatewayUserService userService;
    @Autowired
    private ReportGetService reportGetService;
    @Autowired
    private SysDictService sysDictService;

    @Autowired
    private ReportContentService reportContentService;

    @Value("${absolutepathReport}")
    private String absolutepathReport;

    @Autowired
    private ModelTestService modelTestService;

    @Autowired
    CreditReportCustomService customService;

    @RequestMapping(value = "/getReportCountColums.json")
    public RestServiceResult<List<OptionalColumn>> getReportCountColums() {
        return new RestServiceResult<List<OptionalColumn>>(ReportEnum.getOptionalColumns());
    }

    @RequestMapping(value = "/getDefaultReportCountColums.json")
    public RestServiceResult<List<String>> getDefaultReportCountColums() {
        return new RestServiceResult<List<String>>(ReportEnum.getDefaultShowColumnEN());
    }

    @RequestMapping(value = "/getAdvancedReportCountColums.json")
    public RestServiceResult<List<OptionalColumn>> getAdvancedReportCountColums() {
        return new RestServiceResult<List<OptionalColumn>>(ReportEnum.getAdvancedConditionColumns());
    }

    @RequestMapping(value = "/addReportShowColunms.json")
    public RestServiceResult<String> addReportShowColunms(
            @RequestParam(value = "columns", required = true) String[] columns, HttpServletRequest request) {
        RestServiceResult<String> result = new RestServiceResult<String>();
        // 获取当前用户信息
        RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("AchievementController#addShowColunms", "未获取到当前用户信息！");
                return result;
            }
            String column = StringUtils.join(columns, ",");
            MapCache.set(userInfo.getId() + "_" + REPORT_COUNT_ID, StringUtils.split(column, ","));
        } else {
            result.setCode(user.getCode());
            result.setMsg(user.getMsg());
            return result;
        }
        return new RestServiceResult<String>();
    }

    @RequestMapping(value = "/export")
    public RestServiceResult<List<Map<String, Object>>> exportData(
            @RequestParam(value = "reportType", defaultValue = "", required = true) String reportType,
            @RequestParam(value = "mainType", defaultValue = "", required = true) String mainType,
            @RequestParam(value = "recieveStatus", defaultValue = "", required = true) String recieveStatus,
            @RequestParam(value = "condition", defaultValue = "", required = true) String condition,
            @RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN, Page page,
            HttpServletResponse response, HttpServletRequest request) {
        page.setLimit(1000);
        List<String> showColumns = JSONArray.parseArray(columnEN, String.class);
        List<OptionalColumn> optionalColumns = ReportEnum.getOptionalColumns();
        List<Map<String, Object>> data;
        RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
        RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("AchievementController#getAchievementCount", "未获取到当前用户信息！");
                return result;
            }
        } else {
            result.setCode(user.getCode());
            result.setMsg(user.getMsg());
            return result;
        }
        try {
            data = reportGetService.selectAllReportGet(reportType, mainType, recieveStatus, showColumns, null,
                    condition, page);
            if (RestServiceResult.CODE_SUCCESS != result.getCode()) {
                return result;
            }
            ExcelUtil.downloadExcel(response, data, "报告领取列表", "报告领取列表", showColumns, optionalColumns);
            return result;
        } catch (Exception e) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("报告领取导出异常，请稍后再试！");
            ExceptionLogger.error("报告领取导出异常！", e.getMessage(), e);
            return result;
        }
    }

    @RequestMapping(value = "/selectAllReportGet.json")
    public RestServiceResult<List<Map<String, Object>>> selectAllReportGet(
            @RequestParam(value = "reportType", defaultValue = "", required = true) String reportType,
            @RequestParam(value = "mainType", defaultValue = "", required = true) String mainType,
            @RequestParam(value = "recieveStatus", defaultValue = "", required = true) String recieveStatus,
            @RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
            HttpServletRequest request) {
        RestServiceResult<List<Map<String, Object>>> r = new RestServiceResult<List<Map<String, Object>>>();
        List<Map<String, Object>> rep = new ArrayList<Map<String, Object>>();
        RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                r.setCode(RestServiceResult.CODE_UNKNOW);
                r.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("AchievementController#getAchievementCount", "未获取到当前用户信息！");
                return r;
            }
        } else {
            r.setCode(user.getCode());
            r.setMsg(user.getMsg());
            return r;
        }
        String[] configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + REPORT_COUNT_ID);
        List<String> showColumns = (configColumns == null || configColumns.length == 0)
                ? ReportEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
        List<Map<String, Object>> data;
        try {
            rep = reportGetService.selectAllReportGet(reportType, mainType, recieveStatus, showColumns,
                    new String[]{"id"}, condition, page);
            r.setCount(page.getTotalCount());
        } catch (Exception e) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg(e.getMessage());
            ExceptionLogger.error("reportGet#selectAllReportGet", "报告信息查询失败");
        }
        r.setData(rep);
        return r;
    }

    @RequestMapping(value = "/selectReportHistoryForPage.json")
    public RestServiceResult<List<Map<String, Object>>> selectReportHistoryForPage(
            @RequestParam(value = "bgbh", required = true) String bgbh,
            @RequestParam(value = "lqr", defaultValue = "", required = true) String lqr, Page page) {
        RestServiceResult<List<Map<String, Object>>> r = new RestServiceResult<List<Map<String, Object>>>();
        List<Map<String, Object>> rep = new ArrayList<Map<String, Object>>();
        try {
            rep = reportGetService.selectReportHistoryForPage(bgbh, lqr, page);
            r.setCount(page.getTotalCount());
        } catch (Exception e) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg(e.getMessage());
            ExceptionLogger.error("reportGet#selectReportHistoryForPage", "报告历史信息查询失败");
        }
        r.setData(rep);
        return r;
    }

    @RequestMapping(value = "/updateReportshzt.json")
    public RestServiceResult updateReportshzt(@RequestParam(value = "bgbh", required = true) String bgbh,
                                              @RequestParam(value = "id", required = true) String id,
                                              @RequestParam(value = "lqr", required = true) String lqr,
                                              @RequestParam(value = "lqtype", required = true) String lqtype,
                                              @RequestParam(value = "lqbz", required = true) String lqbz,
                                              @RequestParam(value = "file", required = true) String file) {
        RestServiceResult r = new RestServiceResult();
        try {
            reportGetService.updateReportshzt(bgbh, id, lqr, lqtype, lqbz, file);
            r.setMsg("报告资料提交成功");
        } catch (Exception e) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg(e.getMessage());
            ExceptionLogger.error("reportGet#updateReportshzt", "报告资料提交失败");
        }
        return r;
    }

    @RequestMapping(value = "/isReportFile.json")
    public RestServiceResult isReportFile(@RequestParam(value = "fileUrl", required = true) String fileUrl,
                                          HttpServletRequest request) {
        RestServiceResult r = new RestServiceResult();
        RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                r.setCode(RestServiceResult.CODE_UNKNOW);
                r.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("AchievementController#getAchievementCount", "未获取到当前用户信息！");
            }
        } else {
            r.setCode(user.getCode());
            r.setMsg(user.getMsg());

        }
        File file = new File(fileUrl);
        if (!file.exists()) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg("暂无报告资料");
            ExceptionLogger.error("reportGet#isReportFile", "暂无报告资料");
        }
        return r;

    }

    @RequestMapping(value = "/downReportFile.json")
    public void downReportFile(@RequestParam(value = "fileUrl", required = true) String fileUrl,
                               HttpServletResponse response, HttpServletRequest request) {
        RestServiceResult r = new RestServiceResult();
        RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                r.setCode(RestServiceResult.CODE_UNKNOW);
                r.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("AchievementController#getAchievementCount", "未获取到当前用户信息！");
            }
        } else {
            r.setCode(user.getCode());
            r.setMsg(user.getMsg());

        }
        if (!FileUtil.downloadFile(fileUrl, response)) {
            r.setMsg("下载失败，请稍后再试");
            ExceptionLogger.error("reportGet#downReportFile", "报告资料领取失败");
        }

    }

    @RequestMapping(value = "/updateReportWj.json")
    public RestServiceResult<Map<String, String>> updateReportWj(MultipartFile file) {
        RestServiceResult<Map<String, String>> r = new RestServiceResult<Map<String, String>>();
        Map<String, String> map = new HashMap<String, String>();
        if (!file.getOriginalFilename().toLowerCase().endsWith(".zip")
                && !file.getOriginalFilename().toLowerCase().endsWith(".rar")
                && !file.getOriginalFilename().toLowerCase().endsWith(".7z")) {
            r.setMsg("压缩包格式错误");
        }
        if (file.getSize() > 10 * 1024) {
            r.setMsg("文件大小超过10M");
        }
        String dirPath = absolutepathReport + File.separator + "领取凭证_" + File.separator + UuidUtil.getUUid();
        try {
            map.put("fileUrl", dirPath + File.separator + "领取凭证_" + file.getOriginalFilename());
            r.setData(map);
            userService.fileUpload(file, dirPath, "领取凭证_");
        } catch (Exception e) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg(e.getMessage());
            ExceptionLogger.error("reportGet#updateReportWj", "压缩包上传失败");
        }
        return r;
    }

    // 前台高级搜索
    @RequestMapping(value = "/getQTReportCountColums.json")
    public RestServiceResult<List<OptionalColumn>> getQTReportCountColums() {
        return new RestServiceResult<List<OptionalColumn>>(RepQTGetEnum.getOptionalColumns());
    }

    @RequestMapping(value = "/getQTDefaultReportCountColums.json")
    public RestServiceResult<List<String>> getQTDefaultReportCountColums() {
        return new RestServiceResult<List<String>>(RepQTGetEnum.getDefaultShowColumnEN());
    }

    @RequestMapping(value = "/getQTAdvancedReportCountColums.json")
    public RestServiceResult<List<OptionalColumn>> getQTAdvancedReportCountColums() {
        return new RestServiceResult<List<OptionalColumn>>(RepQTGetEnum.getAdvancedConditionColumns());
    }

    @RequestMapping(value = "/addQTShowColunms.json")
    public RestServiceResult<String> addQTShowColunms(
            @RequestParam(value = "columns", required = true) String[] columns, HttpServletRequest request) {
        RestServiceResult<String> result = new RestServiceResult<String>();
        // 获取当前用户信息
        RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("AchievementController#addShowColunms", "未获取到当前用户信息！");
                return result;
            }
            String column = StringUtils.join(columns, ",");
            MapCache.set(userInfo.getId() + "_" + REPORT_HISTORY_COUNT_ID, StringUtils.split(column, ","));
        } else {
            result.setCode(user.getCode());
            result.setMsg(user.getMsg());
            return result;
        }
        return new RestServiceResult<String>();
    }

    @RequestMapping(value = "/QTexport")
    public RestServiceResult<List<Map<String, Object>>> QTexport(
            @RequestParam(value = "reportType", defaultValue = "", required = true) String reportType,
            @RequestParam(value = "mainType", defaultValue = "", required = true) String mainType,
            @RequestParam(value = "condition", defaultValue = "", required = true) String condition,
            @RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN, Page page,
            HttpServletResponse response, HttpServletRequest request) {
        page.setLimit(1000);
        List<String> showColumns = JSONArray.parseArray(columnEN, String.class);
        List<OptionalColumn> optionalColumns = RepQTGetEnum.getOptionalColumns();
        List<Map<String, Object>> data;
        RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
        RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("AchievementController#getAchievementCount", "未获取到当前用户信息！");
                return result;
            }
        } else {
            result.setCode(user.getCode());
            result.setMsg(user.getMsg());
            return result;
        }
        try {
            data = reportGetService.selectQTReportGetByConditionForPage(reportType, mainType, showColumns, null,
                    condition, page);
            if (RestServiceResult.CODE_SUCCESS != result.getCode()) {
                return result;
            }
            ExcelUtil.downloadExcel(response, data, "报告查询", "报告查询", showColumns, optionalColumns);
            return result;
        } catch (Exception e) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("报告查询导出异常，请稍后再试！");
            ExceptionLogger.error("报告查询导出异常！", e.getMessage(), e);
            return result;
        }
    }

    @RequestMapping(value = "/selectQTAllReportGet.json")
    public RestServiceResult<List<Map<String, Object>>> selectQTAllReportGet(
            @RequestParam(value = "reportType", defaultValue = "", required = true) String reportType,
            @RequestParam(value = "mainType", defaultValue = "", required = true) String mainType,
            @RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
            HttpServletRequest request) {
        RestServiceResult<List<Map<String, Object>>> r = new RestServiceResult<List<Map<String, Object>>>();
        List<Map<String, Object>> rep = new ArrayList<Map<String, Object>>();
        RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                r.setCode(RestServiceResult.CODE_UNKNOW);
                r.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("reportGet#selectQTHistoryAllReportGet", "未获取到当前用户信息！");
                return r;
            }
        } else {
            r.setCode(user.getCode());
            r.setMsg(user.getMsg());
            return r;
        }
        String[] configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + REPORT_HISTORY_COUNT_ID);
        List<String> showColumns = (configColumns == null || configColumns.length == 0)
                ? RepQTGetEnum.getDefaultShowColumnEN() : Arrays.asList(configColumns);
        List<Map<String, Object>> data;
        try {
            rep = reportGetService.selectQTReportGetByConditionForPage(reportType, mainType, showColumns,
                    new String[]{"id,reportStatus"}, condition, page);
            r.setCount(page.getTotalCount());
        } catch (Exception e) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg(e.getMessage());
            ExceptionLogger.error("reportGet#selectAllReportGet", "前台报告信息查询失败");
        }
        r.setData(rep);
        return r;
    }

    // 前台历史查询

    @RequestMapping(value = "/getQTHistoryReportCountColums.json")
    public RestServiceResult<List<OptionalColumn>> getQTHistoryReportCountColums() {
        return new RestServiceResult<List<OptionalColumn>>(RepQTGetHistory.getOptionalColumns());
    }

    @RequestMapping(value = "/getQTHistoryDefaultReportCountColums.json")
    public RestServiceResult<List<String>> getQTHistoryDefaultReportCountColums() {
        return new RestServiceResult<List<String>>(RepQTGetHistory.getDefaultShowColumnEN());
    }

    @RequestMapping(value = "/getQTHistoryAdvancedReportCountColums.json")
    public RestServiceResult<List<OptionalColumn>> getQTHistoryAdvancedReportCountColums() {
        return new RestServiceResult<List<OptionalColumn>>(RepQTGetHistory.getAdvancedConditionColumns());
    }

    @RequestMapping(value = "/addQTHistoryShowColunms.json")
    public RestServiceResult<String> addQTHistoryShowColunms(
            @RequestParam(value = "columns", required = true) String[] columns, HttpServletRequest request) {
        RestServiceResult<String> result = new RestServiceResult<String>();
        // 获取当前用户信息
        RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("AchievementController#addShowColunms", "未获取到当前用户信息！");
                return result;
            }
            String column = StringUtils.join(columns, ",");
            MapCache.set(userInfo.getId() + "_" + QT_REPORT_HISTORY_COUNT, StringUtils.split(column, ","));
        } else {
            result.setCode(user.getCode());
            result.setMsg(user.getMsg());
            return result;
        }
        return new RestServiceResult<String>();
    }

    @RequestMapping(value = "/QTHistoryexport")
    public RestServiceResult<List<Map<String, Object>>> QTHistoryexport(
            @RequestParam(value = "bgbh", defaultValue = "", required = true) String bgbh,
            @RequestParam(value = "condition", defaultValue = "", required = true) String condition,
            @RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN, Page page,
            HttpServletResponse response, HttpServletRequest request) {
        page.setLimit(1000);
        List<String> showColumns = JSONArray.parseArray(columnEN, String.class);
        List<OptionalColumn> optionalColumns = RepQTGetHistory.getOptionalColumns();
        List<Map<String, Object>> data;
        RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
        RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("AchievementController#getAchievementCount", "未获取到当前用户信息！");
                return result;
            }
        } else {
            result.setCode(user.getCode());
            result.setMsg(user.getMsg());
            return result;
        }
        try {
            data = reportGetService.selectQTReportGetHistoryByConditionForPage(bgbh, showColumns, null, condition,
                    page);
            if (RestServiceResult.CODE_SUCCESS != result.getCode()) {
                return result;
            }
            ExcelUtil.downloadExcel(response, data, "报告查询历史", "报告查询历史", showColumns, optionalColumns);
            return result;
        } catch (Exception e) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("报告查询历史导出异常，请稍后再试！");
            ExceptionLogger.error("报告查询历史导出异常！", e.getMessage(), e);
            return result;
        }
    }

    @RequestMapping(value = "/selectQTHistoryAllReportGet.json")
    public RestServiceResult<List<Map<String, Object>>> selectQTHistoryAllReportGet(
            @RequestParam(value = "bgbh", required = true) String bgbh,
            @RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
            HttpServletRequest request) {
        RestServiceResult<List<Map<String, Object>>> r = new RestServiceResult<List<Map<String, Object>>>();
        List<Map<String, Object>> rep = new ArrayList<Map<String, Object>>();
        RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                r.setCode(RestServiceResult.CODE_UNKNOW);
                r.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("reportGet#selectQTHistoryAllReportGet", "未获取到当前用户信息！");
                return r;
            }
        } else {
            r.setCode(user.getCode());
            r.setMsg(user.getMsg());
            return r;
        }
        String[] configColumns = (String[]) MapCache.get(userInfo.getId() + "_" + QT_REPORT_HISTORY_COUNT);
        List<String> showColumns = (configColumns == null || configColumns.length == 0)
                ? RepQTGetHistory.getDefaultShowColumnEN() : Arrays.asList(configColumns);
        List<Map<String, Object>> data;
        try {
            rep = reportGetService.selectQTReportGetHistoryByConditionForPage(bgbh, showColumns, null, condition, page);
            r.setCount(page.getTotalCount());
        } catch (Exception e) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg(e.getMessage());
            ExceptionLogger.error("reportGet#selectQTHistoryAllReportGet", "前台报告历史查询失败");
        }
        r.setData(rep);
        return r;
    }

    @RequestMapping(value = "/reportExport.do")
    public RestServiceResult<List<Map<String, Object>>> reportExport(
            @RequestParam(value = "bgbh", required = true) String bgbh, String id, HttpServletRequest request) {
        RestServiceResult<List<Map<String, Object>>> r = new RestServiceResult<List<Map<String, Object>>>();
        List<Map<String, Object>> rep = new ArrayList<Map<String, Object>>();
        RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                r.setCode(RestServiceResult.CODE_UNKNOW);
                r.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("reportGet#selectQTHistoryAllReportGet", "未获取到当前用户信息！");
                return r;
            }
        } else {
            r.setCode(user.getCode());
            r.setMsg(user.getMsg());
            return r;
        }
        try {
            int returnVal = reportGetService.reportExport(bgbh, id, pdfForXypjPagePath, pdfJsPath, absolutepath,
                    googlePath, request, String.valueOf(userInfo.getId()));
            if (returnVal == -1) {
                r.setCode(RestServiceResult.CODE_UNKNOW);
                r.setMsg("生成报告失败");
                ExceptionLogger.error("reportGet#selectQTHistoryAllReportGet", "生成报告失败");
            }
        } catch (Exception e) {
            reportGetService.updateReportStatusByBgbh("xypj_evalInfo", "3", bgbh);
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg(e.getMessage());
            ExceptionLogger.error("reportGet#selectQTHistoryAllReportGet", "生成报告失败");
        }
        r.setData(rep);
        return r;
    }

    @RequestMapping(value = "/reportExportAllYz.do")
    public RestServiceResult<List<Map<String, Object>>> reportExportAllYz(
            @RequestParam(value = "pcId", required = true) String pcId,
            @RequestParam(value = "pch", required = true) String pch) {
        RestServiceResult<List<Map<String, Object>>> r = new RestServiceResult<>();
        List<Map<String, Object>> rep = new ArrayList<>();
        String table = "";
        String tablePc = "";
        try {
            long start = System.currentTimeMillis();
            List<Map<String, String>> listE = new ArrayList<Map<String, String>>();
            if (pch.indexOf("M") > -1) {
                table = "xypj_model_test_detail";
                tablePc = "xypj_model_test_pc";
            } else {
                table = "xypj_score_running_detail";
                tablePc = "xypj_model_test_pc";
            }
            listE = reportGetService.selectEnterpriseByPc(table, pcId);
            reportGetService.updateReportStatus(tablePc, "1", pcId);
            reportGetService.updateReportStatusBypcId(table, "1", pcId);
            String url = pdfForXypjPagePathYz;
            for (int i = 0; i < listE.size(); i++) {
                Map<String, String> pcDetail = reportGetService.selectPcDetail(table, listE.get(i).get("tybm"), pcId);
                String bgbh = pcDetail.get("bgbh");
                String score = String.valueOf(pcDetail.get("score"));
                String rank = pcDetail.get("rank");
                String evalInfo = pcDetail.get("bgbh");
                url = url + "?tybm=" + listE.get(i).get("tybm") + "&pcId=" + pcId + "&bgbh=" + bgbh + "&score=" + score + "&rank=" + rank + "&evalInfo=" + evalInfo + "&qymc=" + listE.get(i).get("mainName");
                boolean googleConvent = HtmlToPdfUtils.googleConventSync(pdfJsPath,
                        url,
                        absolutepath + ResourcePath.CREDIT_REPORT_DIR + pch, listE.get(i).get("mainName") + ".pdf", null, false,
                        googlePath);
                if (!googleConvent) {
                    r.setCode(RestServiceResult.CODE_UNKNOW);
                    r.setMsg("生成报告失败");
                    ExceptionLogger.error("reportGet#selectQTHistoryAllReportGet", "生成报告失败");
                    return r;
                }
            }
            long end = System.currentTimeMillis();
            System.out.println(end - start);
            FileUtils.compressedFile(absolutepath + ResourcePath.CREDIT_REPORT_DIR + pch, absolutepath + ResourcePath.CREDIT_REPORT_DIR_ZIP);
            long stop = System.currentTimeMillis();
            System.out.println(stop - end);
            reportGetService.updateReportStatus(tablePc, "2", pcId);
            reportGetService.updateReportStatusBypcId(table, "2", pcId);
        } catch (Exception e) {
            reportGetService.updateReportStatus(tablePc, "3", pcId);
            reportGetService.updateReportStatusBypcId(table, "3", pcId);
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg(e.getMessage());
            ExceptionLogger.error("reportGet#selectQTHistoryAllReportGet", "生成报告失败");
            return r;
        }
        r.setData(rep);
        return r;
    }

    @RequestMapping(value = "/reportExportAllYzThread.do")
    public RestServiceResult<List<Map<String, Object>>> reportExportAllYzThread(
            @RequestParam(value = "pcId", required = true) String pcId,
            @RequestParam(value = "pch", required = true) String pch, Page page, HttpServletRequest request) {
        RestServiceResult<List<Map<String, Object>>> r = new RestServiceResult<List<Map<String, Object>>>();
        List<Map<String, Object>> rep = new ArrayList<Map<String, Object>>();
        try {
            List<Map<String, String>> listE = new ArrayList<Map<String, String>>();
            if (pch.indexOf("M") > -1) {
                listE = reportGetService.selectEnterpriseByPc("xypj_model_test_detail", pcId);
            } else {
                listE = reportGetService.selectEnterpriseByPc("xypj_score_running_detail", pcId);
            }
            int poolSize = 10;
            ExecutorService es = Executors.newFixedThreadPool(poolSize);
            List<Future> list = new ArrayList<Future>();
            for (int i = 0; i < poolSize; i++) {
                Callable c = new ThreadExportCallable(averageAssign(listE, poolSize).get(i), pdfForXypjPagePathYz,
                        pdfJsPath, absolutepath, googlePath, pch, pcId);
                Future f = es.submit(c);
                list.add(f);
            }
            es.shutdown();
            FileUtils.compressedFile(absolutepath + ResourcePath.CREDIT_REPORT_DIR + pch,
                    absolutepath + ResourcePath.CREDIT_REPORT_DIR_ZIP);
        } catch (Exception e) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg(e.getMessage());
            ExceptionLogger.error("reportGet#selectQTHistoryAllReportGet", "生成报告失败");
            return r;
        }
        r.setData(rep);
        return r;
    }

    /**
     * 将一组数据平均分成n组
     *
     * @param source 要分组的数据源
     * @param n      平均分成n组
     * @param <T>
     * @return
     */
    public static <T> List<List<T>> averageAssign(List<T> source, int n) {
        List<List<T>> result = new ArrayList<List<T>>();
        int remainder = source.size() % n; // (先计算出余数)
        int number = source.size() / n; // 然后是商
        int offset = 0;// 偏移量
        for (int i = 0; i < n; i++) {
            List<T> value = null;
            if (remainder > 0) {
                value = source.subList(i * number + offset, (i + 1) * number + offset + 1);
                remainder--;
                offset++;
            } else {
                value = source.subList(i * number + offset, (i + 1) * number + offset);
            }
            result.add(value);
        }
        return result;
    }

    @RequestMapping(value = "/reportExportYz.do")
    public RestServiceResult<List<Map<String, Object>>> reportExportYz(
            @RequestParam(value = "mainName", required = true) String mainName, String tybm, String pcId, String id,
            String pch, Page page, HttpServletRequest request) {
        RestServiceResult<List<Map<String, Object>>> r = new RestServiceResult<List<Map<String, Object>>>();
        List<Map<String, Object>> rep = new ArrayList<Map<String, Object>>();
        String table = "";
        if (pch.indexOf("M") > -1) {
            table = "xypj_model_test_detail";
        } else {
            table = "xypj_score_running_detail";
        }
        reportGetService.updateReportStatus(table, "1", id);
        try {
            //TODO 使用Freemarker模板生成PDF文件
            Map<String, Object> templateData = this.getTemplateData(pcId, tybm);
            String filePath = absolutepath + ResourcePath.CREDIT_REPORT_DIR + pch;
            boolean googleConvent = FreeeMarkerUtils.html2Pdf(templateData, "/template/pdf_template_freemarker.html", filePath, mainName + ".pdf", absolutepath);

//            String url = pdfForXypjPagePathYz + "?tybm=" + tybm + "&qymc=" + mainName + "&pcId=" + pcId;
//            boolean googleConvent = HtmlToPdfUtils.googleConventSync(pdfJsPath, url,
//                    absolutepath + ResourcePath.CREDIT_REPORT_DIR + pch, mainName + ".pdf", null, false, googlePath);
            if (googleConvent) {
                reportGetService.updateReportStatusByBgbh(table, "2", id);
                // reportGetService.insertPrintHistory((String.valueOf(m.get("id"))),String.valueOf(m.get("score")),String.valueOf("2"));
                r.setData(rep);
                return r;
            } else {
                reportGetService.updateReportStatusByBgbh(table, "3", id);
                r.setCode(RestServiceResult.CODE_UNKNOW);
                r.setMsg("生成报告失败");
                ExceptionLogger.error("reportGet#selectQTHistoryAllReportGet", "生成报告失败");
            }
        } catch (Exception e) {
            reportGetService.updateReportStatusByBgbh(table, "3", id);
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg(e.getMessage());
            ExceptionLogger.error("reportGet#selectQTHistoryAllReportGet", "前台报告历史查询失败");
        }
        r.setData(rep);
        return r;
    }



    @RequestMapping(value = "/updateReportStatus.do")
    public RestServiceResult<List<Map<String, Object>>> updateReportStatus(String id,
            String pch, String flag) {
        RestServiceResult<List<Map<String, Object>>> r = new RestServiceResult<List<Map<String, Object>>>();
        List<Map<String, Object>> rep = new ArrayList<Map<String, Object>>();
        String table = "";
        if (pch.indexOf("M") > -1) {
            table = "xypj_model_test_detail";
        } else {
            table = "xypj_score_running_detail";
        }
        try {
            if (StringUtils.equals("1", flag)) {
                reportGetService.updateReportStatusByBgbh(table, "2", id);
                r.setData(rep);
                return r;
            } else {
                reportGetService.updateReportStatusByBgbh(table, "3", id);
                r.setCode(RestServiceResult.CODE_UNKNOW);
                r.setMsg("生成报告失败");
                ExceptionLogger.error("reportGet#selectQTHistoryAllReportGet", "生成报告失败");
            }
        } catch (Exception e) {
            reportGetService.updateReportStatusByBgbh(table, "3", id);
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg(e.getMessage());
            ExceptionLogger.error("reportGet#selectQTHistoryAllReportGet", "前台报告历史查询失败");
        }
        r.setData(rep);
        return r;
    }

    /**
     * 文件下载
     *
     * @param bgbh     规则id
     * @param request
     * @param response
     */
    @RequestMapping(value = "/download.json")
    @ResponseBody
    public void download(@RequestParam(value = "bgbh", defaultValue = "", required = true) String bgbh,
                         HttpServletRequest request, HttpServletResponse response) {
        String path = absolutepath + File.separator + "reports" + File.separator;
        path += bgbh;
        Map m = reportContentService.getEvalInfo(bgbh);
        String ztmc = String.valueOf(m.get("ztmc"));
        path += File.separator + ztmc + ".pdf";
        FileUtil.uploadFile(path, request, response);
    }

    /**
     * 文件下载
     *
     * @param bgbh     规则id
     * @param request
     * @param response
     */
    @RequestMapping(value = "/downloadSingle.json")
    @ResponseBody
    public void downloadSingle(String pch, String bgbh, String mainName, HttpServletRequest request,
                               HttpServletResponse response) {
        String path = absolutepath + ResourcePath.CREDIT_REPORT_DIR;
        path += pch + File.separator;
        path += mainName + ".pdf";
        FileUtil.uploadFile(path, request, response);
    }

    /**
     * 文件下载
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/downloadZip.json")
    @ResponseBody
    public void downloadZip(String pch, String pcId, HttpServletRequest request, HttpServletResponse response) {
        String path = absolutepath + ResourcePath.CREDIT_REPORT_DIR_ZIP;
        path += pch + ".zip";
        FileUtil.uploadFile(path, request, response);
    }

    @RequestMapping(value = "/getEvaDictory.json")
    public RestServiceResult getEvaDictory() {
        RestServiceResult r = new RestServiceResult<List<DictDetailEntity>>();
        Map<String, Object> map = new HashMap<>();
        try {
            List<DictDetailEntity> list = sysDictService.getDictDetails(BGLX, StringUtils.EMPTY);
            map.put(BGLX, list);
            r.setData(map);
            return r;
        } catch (Exception e) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg("字典值查询失败！");
            return r;
        }
    }

    @RequestMapping(value = "/selectPrintHistory.json")
    public RestServiceResult<List<Map>> selectPrintHistory(String id, HttpServletResponse response,
                                                           HttpServletRequest request) {
        String token = HttpServletHelper.getUserToken(request);
        RestServiceResult<List<Map>> result = new RestServiceResult<List<Map>>();
        // 获取当前用户信息
        RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
                return result;
            }
        } else {
            result.setCode(user.getCode());
            result.setMsg(user.getMsg());
            return result;
        }
        try {
            List<Map> list = reportGetService.selectPrintHistory(id);
            result.setData(list);
            return result;
        } catch (Exception e) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("获取规则列表异常，请稍后再试！");
            ExceptionLogger.error("获取规则列表异常！", e.getMessage(), e);
            return result;
        }
    }

    /**
     * 查看报告
     *
     * @param bgbh 报告编号
     * @return
     */
    @RequestMapping(value = "/openReport.json")
    public void openReport(@RequestParam(value = "ztmc", defaultValue = "", required = true) String ztmc,
                           @RequestParam(value = "bgbh", defaultValue = "", required = true) String bgbh, HttpServletResponse response)
            throws IOException {

        String path = absolutepath + File.separator + "reports" + File.separator;
        path += bgbh;
        path += File.separator + ztmc + ".pdf";

        response.setContentType("application/pdf");

        ServletOutputStream outputStream = response.getOutputStream();

        response.setHeader("Content-Disposition", "inline;fileName=" + ztmc + ".pdf");

        File pdf = null;
        FileInputStream fis = null;
        byte[] buffer = new byte[1024 * 1024];
        pdf = new File(path);
        response.setContentLength((int) pdf.length());
        fis = new FileInputStream(pdf);
        int readBytes = -1;
        while ((readBytes = fis.read(buffer, 0, 1024 * 1024)) != -1) {
            outputStream.write(buffer, 0, 1024 * 1024);
        }
        outputStream.close();
        fis.close();
    }

    /**
     * 查看报告
     *
     * @param bgbh 报告编号
     * @return
     */
    @RequestMapping(value = "/openReportViewInBatch.json")
    public void openReportViewInBatch(
            @RequestParam(value = "mainName", defaultValue = "", required = true) String mainName,
            @RequestParam(value = "pch", defaultValue = "", required = true) String pch,
            @RequestParam(value = "bgbh", defaultValue = "", required = true) String bgbh, HttpServletResponse response)
            throws IOException {

        String path = absolutepath + File.separator + "reports" + File.separator;
        path += pch + File.separator;
        path += mainName + ".pdf";

        response.setContentType("application/pdf");

        ServletOutputStream outputStream = response.getOutputStream();
        response.setHeader("Content-Disposition", "inline;fileName=" + mainName + ".pdf");
        File pdf = null;
        FileInputStream fis = null;
        byte[] buffer = new byte[1024 * 1024];
        pdf = new File(path);
        response.setContentLength((int) pdf.length());
        fis = new FileInputStream(pdf);
        int readBytes = -1;
        while ((readBytes = fis.read(buffer, 0, 1024 * 1024)) != -1) {
            outputStream.write(buffer, 0, 1024 * 1024);
        }
        outputStream.close();
        fis.close();
    }

    /**
     * 获取生成PDF所需要的数据
     *
     * @param pcId
     * @param tybm
     * @return
     */
    private Map<String, Object> getTemplateData(String pcId, String tybm) {
        Map<String, Object> result = new HashMap<String, Object>();
        Map<String, String> evalInfo = modelTestService.selectScoreInfoByTybmAndPcid(pcId, tybm);
        result.put("bgbh", StringUtils.isNotBlank(evalInfo.get("bgbh")) ? evalInfo.get("bgbh") : "-");
        result.put("rank", StringUtils.isNotBlank(evalInfo.get("rank")) ? evalInfo.get("rank") : "-");
        result.put("evalInfo", StringUtils.isNotBlank(evalInfo.get("evalInfo")) ? evalInfo.get("evalInfo") : "-");

        int honorxxCount = 0, loseCreditCount = 0;
        // 企业工商基础信息
        List<Map> qyxx = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_1000000010014_lfsxnk85kf", tybm);
        if (null != qyxx && qyxx.size() > 0) {
            result.put("A000001", null != qyxx.get(0).get("A000001") ? qyxx.get(0).get("A000001") : "-");
            result.put("A000002", null != qyxx.get(0).get("A000002") ? qyxx.get(0).get("A000002") : "-");
            result.put("A000006", null != qyxx.get(0).get("A000006") ? qyxx.get(0).get("A000006") : "-");
            result.put("djjg", null != qyxx.get(0).get("DJJG") ? qyxx.get(0).get("DJJG") : "-");
            result.put("zs", null != qyxx.get(0).get("ZS") ? qyxx.get(0).get("ZS") : "-");
            result.put("zczb", null != qyxx.get(0).get("ZCZB") ? qyxx.get(0).get("ZCZB") : "-");
            result.put("fddbr", null != qyxx.get(0).get("fddbr") ? qyxx.get(0).get("fddbr") : "-");
            result.put("ygrs", (null != qyxx.get(0).get("ygrs") && !String.valueOf(qyxx.get(0).get("ygrs")).equals("0")) ?
                    ("目前员工数" + qyxx.get(0).get("ygrs") + "人") : "目前员工数暂未统计");
            result.put("clrq", null != qyxx.get(0).get("CLRQ") ? DateUtils.parseDateByFormat(String.valueOf(qyxx.get(0).get("CLRQ")), "yyyy-MM-dd") : "-");
            result.put("jyfw", null != qyxx.get(0).get("JYFW") ? qyxx.get(0).get("JYFW") : "-");
            result.put("hydm", null != qyxx.get(0).get("HYDM") ? qyxx.get(0).get("HYDM") : "-");
        } else {
            result.put("A000001", "-");
            result.put("A000002", "-");
            result.put("A000006", "-");
            result.put("djjg", "-");
            result.put("zs", "-");
            result.put("zczb", "-");
            result.put("fddbr", "-");
            result.put("ygrs", "-");
            result.put("clrq", "-");
            result.put("jyfw", "-");
            result.put("hydm", "-");
        }
        // 历史沿革
        List<Map> changeList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_1000000010009_L6GvGS42NY", tybm);
        if (null != changeList && changeList.size() > 0) {
            StringBuilder changeSb = new StringBuilder();
            for (int i = 0; i < changeList.size(); i++) {
                changeSb.append("<tr>");
                changeSb.append("<td>").append(i + 1).append("</td>");
                changeSb.append("<td>").append(changeList.get(i).get("BGSX")).append("</td>");
                changeSb.append("<td>").append(changeList.get(i).get("BGQNR")).append("</td>");
                changeSb.append("<td>").append(changeList.get(i).get("BGHNR")).append("</td>");
                changeSb.append("<td class='date'>").append(changeList.get(i).get("BGRQ")).append("</td>");
                changeSb.append("</tr>");
            }
            result.put("changeList", changeSb.toString());
        } else {
            result.put("changeList", "<tr><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td></tr>");
        }

        // 董事会主要成员
        List<Map> mainList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_1000000010012_7AnbGEhbmt", tybm);
        if (null != mainList && mainList.size() > 0) {
            StringBuilder mainSb = new StringBuilder();
            for (int i = 0; i < mainList.size(); i++) {
                mainSb.append("<tr>");
                mainSb.append("<td>").append(i + 1).append("</td>");
                mainSb.append("<td>").append(mainList.get(i).get("XM")).append("</td>");
                mainSb.append("<td>").append(mainList.get(i).get("ZW")).append("</td>");
                mainSb.append("</tr>");
            }
            result.put("mainList", mainSb.toString());
        } else {
            result.put("mainList", "<tr><td>-</td><td>-</td><td>-</td></tr>");
        }

        // 股东信息
        List<Map> holderList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_1000000010013_8hPE5lWX7N", tybm);
        if (null != holderList && holderList.size() > 0) {
            StringBuilder holderSb = new StringBuilder();
            for (int i = 0; i < holderList.size(); i++) {
                holderSb.append("<tr>");
                holderSb.append("<td>").append(i + 1).append("</td>");
                holderSb.append("<td>").append(holderList.get(i).get("DP")).append("</td>");
                holderSb.append("<td>").append(holderList.get(i).get("SHRATIO")).append("</td>");
                holderSb.append("</tr>");
            }
            result.put("holderList", holderSb.toString());
        } else {
            result.put("holderList", "<tr><td>-</td><td>-</td><td>-</td></tr>");
        }

        // 分支机构
        List<Map> branchList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_1000000010010_aiPIZu8BZF", tybm);
        if (null != branchList && branchList.size() > 0) {
            StringBuilder branchSb = new StringBuilder();
            for (int i = 0; i < branchList.size(); i++) {
                branchSb.append("<tr>");
                branchSb.append("<td>").append(i + 1).append("</td>");
                branchSb.append("<td>").append(branchList.get(i).get("QYMC")).append("</td>");
                branchSb.append("<td>").append(branchList.get(i).get("TYXYDM")).append("</td>");
                branchSb.append("<td>").append(branchList.get(i).get("FZR")).append("</td>");
                branchSb.append("<td>").append(branchList.get(i).get("ZS")).append("</td>");
                branchSb.append("</tr>");
            }
            result.put("branchList", branchSb.toString());
        } else {
            result.put("branchList", "<tr><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td></tr>");
        }

        // 企业对外投资
        List<Map> enterpriseForeignInvestmentList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_10000020035_31QqrjNQMI", tybm);
        if (null != enterpriseForeignInvestmentList && enterpriseForeignInvestmentList.size() > 0) {
            StringBuilder efiSb = new StringBuilder();
            for (int i = 0; i < enterpriseForeignInvestmentList.size(); i++) {
                efiSb.append("<tr>");
                efiSb.append("<td>").append(i + 1).append("</td>");
                efiSb.append("<td>").append(enterpriseForeignInvestmentList.get(i).get("btzqymc")).append("</td>");
                efiSb.append("<td>").append(enterpriseForeignInvestmentList.get(i).get("czfs")).append("</td>");
                efiSb.append("<td>").append(enterpriseForeignInvestmentList.get(i).get("czbl")).append("</td>");
                efiSb.append("<td>").append(enterpriseForeignInvestmentList.get(i).get("qyzt")).append("</td>");
                efiSb.append("</tr>");
            }
            result.put("enterpriseForeignInvestmentList", efiSb.toString());
        } else {
            result.put("enterpriseForeignInvestmentList", "<tr><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td></tr>");
        }

        // 法人对外投资
        List<Map> frForeignInvestmentList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_10000020038_CdPdYlgJIU", tybm);
        if (null != frForeignInvestmentList && frForeignInvestmentList.size() > 0) {
            StringBuilder ffiSb = new StringBuilder();
            for (int i = 0; i < frForeignInvestmentList.size(); i++) {
                ffiSb.append("<tr>");
                ffiSb.append("<td>").append(i + 1).append("</td>");
                ffiSb.append("<td>").append(frForeignInvestmentList.get(i).get("frdwtzqymc")).append("</td>");
                ffiSb.append("<td>").append(frForeignInvestmentList.get(i).get("czfs")).append("</td>");
                ffiSb.append("<td>").append(frForeignInvestmentList.get(i).get("czbl")).append("</td>");
                ffiSb.append("<td>").append(frForeignInvestmentList.get(i).get("qyzt")).append("</td>");
                ffiSb.append("</tr>");
            }
            result.put("frForeignInvestmentList", ffiSb.toString());
        } else {
            result.put("frForeignInvestmentList", "<tr><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td></tr>");
        }

        // 网站备案
        List<Map> webList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_10000020067_zwmkA93VJk", tybm);
        if (null != webList && webList.size() > 0) {
            StringBuilder webSb = new StringBuilder();
            for (int i = 0; i < webList.size(); i++) {
                webSb.append("<tr>");
                webSb.append("<td>").append(i + 1).append("</td>");
                webSb.append("<td>").append(webList.get(i).get("wz")).append("</td>");
                webSb.append("<td>").append(webList.get(i).get("ym")).append("</td>");
                webSb.append("<td>").append(webList.get(i).get("xkz")).append("</td>");
                webSb.append("<td class='date'>").append(webList.get(i).get("jcsj")).append("</td>");
                webSb.append("</tr>");
            }
            result.put("webList", webSb.toString());
        } else {
            result.put("webList", "<tr><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td></tr>");
        }

        // 执行公告
        List<Map> executiveAnnouncementList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_10000020055_ooWilKgE1a", tybm);
        if (null != executiveAnnouncementList && executiveAnnouncementList.size() > 0) {
            loseCreditCount += executiveAnnouncementList.size();
            StringBuilder eaSb = new StringBuilder();
            for (int i = 0; i < executiveAnnouncementList.size(); i++) {
                eaSb.append("<tr>");
                eaSb.append("<td>").append(i + 1).append("</td>");
                eaSb.append("<td>").append(executiveAnnouncementList.get(i).get("ah")).append("</td>");
                eaSb.append("<td>").append(executiveAnnouncementList.get(i).get("ajzt")).append("</td>");
                eaSb.append("<td class='date'>").append(executiveAnnouncementList.get(i).get("lasj")).append("</td>");
                eaSb.append("<td>").append(executiveAnnouncementList.get(i).get("fymc")).append("</td>");
                eaSb.append("</tr>");
            }
            result.put("executiveAnnouncementList", eaSb.toString());
        } else {
            result.put("executiveAnnouncementList", "<tr><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td></tr>");
        }

        // 法院公告
        List<Map> courtAnnouncementList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_10000020056_FqHbBIP5wW", tybm);
        if (null != courtAnnouncementList && courtAnnouncementList.size() > 0) {
            loseCreditCount += courtAnnouncementList.size();
            StringBuilder eaSb = new StringBuilder();
            for (int i = 0; i < courtAnnouncementList.size(); i++) {
                eaSb.append("<tr>");
                eaSb.append("<td>").append(i + 1).append("</td>");
                eaSb.append("<td>").append(courtAnnouncementList.get(i).get("xm")).append("</td>");
                eaSb.append("<td>").append(courtAnnouncementList.get(i).get("gglx")).append("</td>");
                eaSb.append("<td class='date'>").append(courtAnnouncementList.get(i).get("fbsj")).append("</td>");
                eaSb.append("<td>").append(courtAnnouncementList.get(i).get("fymc")).append("</td>");
                eaSb.append("</tr>");
            }
            result.put("courtAnnouncementList", eaSb.toString());
        } else {
            result.put("courtAnnouncementList", "<tr><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td></tr>");
        }

        // 裁判文书
        List<Map> referBookList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_10000020057_VqVvAlMpeL", tybm);
        if (null != referBookList && referBookList.size() > 0) {
            loseCreditCount += referBookList.size();
            StringBuilder referBookSb = new StringBuilder();
            for (int i = 0; i < referBookList.size(); i++) {
                referBookSb.append("<tr>");
                referBookSb.append("<td>").append(i + 1).append("</td>");
                referBookSb.append("<td>").append(referBookList.get(i).get("ah")).append("</td>");
                referBookSb.append("<td>").append(referBookList.get(i).get("ay")).append("</td>");
                referBookSb.append("<td>").append(referBookList.get(i).get("wslx")).append("</td>");
                referBookSb.append("<td class='date'>").append(referBookList.get(i).get("sjsj")).append("</td>");
                referBookSb.append("</tr>");
            }
            result.put("referBookList", referBookSb.toString());
        } else {
            result.put("referBookList", "<tr><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td></tr>");
        }

        // 开庭公告
        List<Map> announcementCourtSessionList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_10000020058_NdGY8UTaWV", tybm);
        if (null != announcementCourtSessionList && announcementCourtSessionList.size() > 0) {
            loseCreditCount += announcementCourtSessionList.size();
            StringBuilder referBookSb = new StringBuilder();
            for (int i = 0; i < announcementCourtSessionList.size(); i++) {
                referBookSb.append("<tr>");
                referBookSb.append("<td>").append(i + 1).append("</td>");
                referBookSb.append("<td>").append(announcementCourtSessionList.get(i).get("ah")).append("</td>");
                referBookSb.append("<td class='date'>").append(announcementCourtSessionList.get(i).get("ktsj")).append("</td>");
                referBookSb.append("<td>").append(announcementCourtSessionList.get(i).get("fymc")).append("</td>");
                referBookSb.append("</tr>");
            }
            result.put("announcementCourtSessionList", referBookSb.toString());
        } else {
            result.put("announcementCourtSessionList", "<tr><td>-</td><td>-</td><td>-</td><td>-</td></tr>");
        }

        // 欠税公告
        List<Map> taxArrearList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_10000020068_omagh7XEue", tybm);
        if (null != taxArrearList && taxArrearList.size() > 0) {
            loseCreditCount += taxArrearList.size();
            StringBuilder taxArrearSb = new StringBuilder();
            for (int i = 0; i < taxArrearList.size(); i++) {
                taxArrearSb.append("<tr>");
                taxArrearSb.append("<td>").append(i + 1).append("</td>");
                taxArrearSb.append("<td>").append(taxArrearList.get(i).get("nsrmc")).append("</td>");
                taxArrearSb.append("<td>").append(taxArrearList.get(i).get("lx")).append("</td>");
                taxArrearSb.append("<td>").append(taxArrearList.get(i).get("qssz")).append("</td>");
                taxArrearSb.append("<td>").append(taxArrearList.get(i).get("qsjr")).append("</td>");
                taxArrearSb.append("</tr>");
            }
            result.put("taxArrearList", taxArrearSb.toString());
        } else {
            result.put("taxArrearList", "<tr><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td></tr>");
        }

        // 行政处罚
        List<Map> adPenaltyList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_10000020047_4z8Y6U03BN", tybm);
        if (null != adPenaltyList && adPenaltyList.size() > 0) {
            loseCreditCount += adPenaltyList.size();
            StringBuilder adPenaltySb = new StringBuilder();
            for (int i = 0; i < taxArrearList.size(); i++) {
                adPenaltySb.append("<tr>");
                adPenaltySb.append("<td>").append(i + 1).append("</td>");
                adPenaltySb.append("<td>").append(adPenaltyList.get(i).get("cfjdws")).append("</td>");
                adPenaltySb.append("<td class='date'>").append(adPenaltyList.get(i).get("cfjdsqfrq")).append("</td>");
                adPenaltySb.append("<td>").append(adPenaltyList.get(i).get("zywfss")).append("</td>");
                adPenaltySb.append("<td>").append(adPenaltyList.get(i).get("cfje")).append("</td>");
                adPenaltySb.append("<td>").append(adPenaltyList.get(i).get("zcxzcfjdjg")).append("</td>");
                adPenaltySb.append("</tr>");
            }
            result.put("adPenaltyList", adPenaltySb.toString());
        } else {
            result.put("adPenaltyList", "<tr><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td></tr>");
        }

        // 失信被执行人
        List<Map> loseCreditList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_10000020053_ixye65DjaA", tybm);
        if (null != loseCreditList && loseCreditList.size() > 0) {
            loseCreditCount += loseCreditList.size();
            StringBuilder loseCreditSb = new StringBuilder();
            for (int i = 0; i < loseCreditList.size(); i++) {
                loseCreditSb.append("<tr>");
                loseCreditSb.append("<td>").append(i + 1).append("</td>");
                loseCreditSb.append("<td>").append(loseCreditList.get(i).get("ah")).append("</td>");
                loseCreditSb.append("<td>").append(loseCreditList.get(i).get("bzxrxm")).append("</td>");
                loseCreditSb.append("<td class='date'>").append(loseCreditList.get(i).get("lasj")).append("</td>");
                loseCreditSb.append("<td>").append(loseCreditList.get(i).get("bzxrdlqk")).append("</td>");
                loseCreditSb.append("<td>").append(loseCreditList.get(i).get("zxfy")).append("</td>");
                loseCreditSb.append("</tr>");
            }
            result.put("loseCreditList", loseCreditSb.toString());
        } else {
            result.put("loseCreditList", "<tr><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td></tr>");
        }

        // 商标注册
        List<Map> logoList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_10000020064_q7zexUMvJF", tybm);
        if (null != logoList && logoList.size() > 0) {
            honorxxCount += logoList.size();
            StringBuilder logoSb = new StringBuilder();
            for (int i = 0; i < logoList.size(); i++) {
                logoSb.append("<tr>");
                logoSb.append("<td>").append(i + 1).append("</td>");
                logoSb.append("<td>").append(logoList.get(i).get("zch")).append("</td>");
                logoSb.append("<td>").append(logoList.get(i).get("sbmc")).append("</td>");
                logoSb.append("<td>").append(logoList.get(i).get("lb")).append("</td>");
                logoSb.append("<td>").append(logoList.get(i).get("zt")).append("</td>");
                logoSb.append("<td class='date'>").append(logoList.get(i).get("sqrq")).append("</td>");
                logoSb.append("</tr>");
            }
            result.put("logoList", logoSb.toString());
            result.put("zzxx", "●企业目前获取" + logoList.size() + "个企业资质信息");
        } else {
            result.put("logoList", "<tr><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td></tr>");
            result.put("zzxx", "●企业目前未获取任何企业资质信息");
        }

        // 知识产权
        List<Map> intellectualPropertyRightList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_10000020065_7ZTo0ASgjr", tybm);
        if (null != intellectualPropertyRightList && intellectualPropertyRightList.size() > 0) {
            honorxxCount += intellectualPropertyRightList.size();
            StringBuilder iprSb = new StringBuilder();
            for (int i = 0; i < intellectualPropertyRightList.size(); i++) {
                iprSb.append("<tr>");
                iprSb.append("<td>").append(i + 1).append("</td>");
                iprSb.append("<td>").append(intellectualPropertyRightList.get(i).get("sqhzlh")).append("</td>");
                iprSb.append("<td>").append(intellectualPropertyRightList.get(i).get("zlmc")).append("</td>");
                iprSb.append("<td>").append(intellectualPropertyRightList.get(i).get("zllx")).append("</td>");
                iprSb.append("<td class='date'>").append(intellectualPropertyRightList.get(i).get("sqrq")).append("</td>");
                iprSb.append("</tr>");
            }
            result.put("intellectualPropertyRightList", iprSb.toString());
        } else {
            result.put("intellectualPropertyRightList", "<tr><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td></tr>");
        }

        // 税务评级
        List<Map> taxRankList = xypjRemoteBaseService.getTableValuesByTybmAndTable("t_10000020066_m4N6fK4BDU", tybm);
        if (null != taxRankList && taxRankList.size() > 0) {
            honorxxCount += taxRankList.size();
            StringBuilder taxRankSb = new StringBuilder();
            for (int i = 0; i < intellectualPropertyRightList.size(); i++) {
                taxRankSb.append("<tr>");
                taxRankSb.append("<td>").append(i + 1).append("</td>");
                taxRankSb.append("<td>").append(taxRankList.get(i).get("nf")).append("</td>");
                taxRankSb.append("<td>").append(taxRankList.get(i).get("nsdj")).append("</td>");
                taxRankSb.append("<td>").append(taxRankList.get(i).get("lx")).append("</td>");
                taxRankSb.append("<td>").append(taxRankList.get(i).get("pjdw")).append("</td>");
                taxRankSb.append("</tr>");
            }
            result.put("taxRankList", taxRankSb.toString());
        } else {
            result.put("taxRankList", "<tr><td>-</td><td>-</td><td>-</td><td>-</td><td>-</td></tr>");
        }

        if (honorxxCount <= 0) {
            result.put("honorxx", "●企业目前未获取任何企业荣誉信息");
        } else {
            result.put("honorxx", "●企业目前获取" + honorxxCount + "个企业荣誉信息");
        }

        if (loseCreditCount <= 0) {
            result.put("losexx", "●经公共信用信息中心数据库查询，该公司在近三年内无失信信息记录");
        } else {
            result.put("losexx", "●经公共信用信息中心数据库查询，该公司在近三年内有" + loseCreditCount + "条失信信息记录");
        }

        result.put("nowTime", DateUtils.getStringOfTodayDate("yyyy年MM月dd日"));
        ReportCustom latest = customService.getLatest();

        result.put("addressBg", "报告出具部门：" + latest.getDept());
        result.put("reportWatermark", latest.getReportWatermark());
        result.put("enterpriseIcon", latest.getEnterpriseIcon());
        return result;
    }
}
